#########################################################################
# File Name: prepare_data.py
# Author: caochenglong
# mail: caochenglong@163.com
# Created Time: 2017-07-24 14:50:43
# Last modified:2017-07-24 15:04:51
#########################################################################
# !/usr/bin/python3
# _*_coding: utf-8_*_

import json
import re
from py2neo import Graph, Node, Relationship


class DataProcessor(object):

    def __init__(self, filename):
        self._filepath = "data/%s" % filename
        self._data = self.get_data()
        self._ids = {}
        self._graph = Graph(password="123")

    def get_data(self):
        data = []
        with open(self._filepath, "r") as f:
            lines = f.readlines()
            for line in lines:
                data.append(json.loads(line))
        return data

    def process(self):
        tx = self._graph.begin()
        for d in self._data:
            for att in d['attr']:
                product = Node("Product", name=d['label'])
                if att == '品牌':
                    attr_list = []
                    if not isinstance(d['attr'][att], list):
                        attr_list.append(d['attr'][att])
                    else:
                        attr_list = d['attr'][att]
                    for brand in attr_list:
                        brand_n = Node("Brand", name=brand)
                        hasProduct = Relationship(
                            product, 'hasBrand', brand_n)
                        hasBrand = Relationship(
                            brand_n, "hasProduct", product)
                        self._graph.create(hasProduct)
                        self._graph.create(hasBrand)
                elif att == '大家说':
                    attr_list = []
                    if not isinstance(d['attr'][att], list):
                        attr_list.append(d['attr'][att])
                    else:
                        attr_list = d['attr'][att]
                    for talk in attr_list:
                        talk = talk.strip()
                        talk_n = Node("Resview", name=talk)
                        hasRsv = Relationship(product, "hasRsv", talk_n)
                        self._graph.create(hasRsv)
                else:
                    attr_list = []
                    if not isinstance(d['attr'][att], list):
                        attr_list.append(d['attr'][att])
                    else:
                        attr_list = d['attr'][att]
                    for at in attr_list:
                        at = at.strip()
                        at_n = Node("Attribute", name=at)
                        hasAtt = Relationship(product, att, at_n)
                        self._graph.create(hasAtt)
        tx.commit()
        print("插入成功")


if __name__ == "__main__":
    dp = DataProcessor("products_more")
    dp.process()
